package com.org.service.impl.sys;

import com.github.pagehelper.Page;
import com.org.core.annotation.ValidationUnique;
import com.org.core.exception.LogicException;
import com.org.core.mybatis.PageUtil;
import com.org.core.mybatis.SqlUtil;
import com.org.core.util.StringUtil;
import com.org.dao.sys.SysUserMapper;
import com.org.entity.base.PageRequest;
import com.org.entity.base.PageResult;
import com.org.entity.sys.SysUser;
import com.org.service.sys.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * 用户 服务实现类
 *
 * @Date 2019/3/7 10:53
 * @author: GuoHonghui
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 新增用户
     *
     * @param sysUser
     * @return
     */
    @Override
    @ValidationUnique(key = {"loginCode"}, msg = {"用户账号已存在！"})
    public int addSysUserInfo(SysUser sysUser) {
        String password = new BCryptPasswordEncoder().encode("123456");
        sysUser.setPassword(password);
        return sysUserMapper.insert(sysUser);
    }

    /**
     * 修改用户
     *
     * @param sysUser
     * @return
     */
    @Override
    @ValidationUnique(key = {"loginCode"}, msg = {"用户账号已存在！"}, excludeSelf = true)
    public int updateSysUserInfo(SysUser sysUser) {
        return sysUserMapper.updateSysUserInfo(sysUser);
    }


    /**
     * 删除用户（单个）
     *
     * @param id
     * @return
     */
    @Override
    public int delSysUserInfo(String id) {
        return sysUserMapper.deleteByPrimaryKey(id);
    }

    /**
     * 删除用户（批量删除）
     *
     * @param ids
     * @return
     */
    @Override
    public int delSysUserList(String ids) {
        String[] idArray = ids.split(",");
        Example example = new Example(SysUser.class);
        example.createCriteria().andIn("id", Arrays.asList(idArray));
        return sysUserMapper.deleteByExample(example);
    }

    /**
     * 根据主键id获取用户详情
     *
     * @param id
     * @return
     */
    @Override
    public SysUser getSysUserInfo(String id) {
        return sysUserMapper.getSysUserInfo(id);
    }

    @Override
    public List<SysUser> getSysUserList(String keyword) {
        return getSysUserExample(keyword);
    }

    /**
     * 获取用户列表
     *
     * @param fkDepartmentCode
     * @param keyword
     * @return
     */
    @Override
    public List<SysUser> getSysUserListByDepartmentCode(String fkDepartmentCode, String keyword) {
        return getSysUserByDepartmentCodeExample(fkDepartmentCode, keyword);
    }

    /**
     * 获取分页用户列表
     *
     * @param keyword
     * @param pageRequest
     * @return
     * @Param fkDepartmentCode
     */
    @Override
    public PageResult<SysUser> getSysUserPageListByDepartmentCode(String fkDepartmentCode, String keyword, PageRequest pageRequest) {
        Page<?> page = PageUtil.startPageAllowNull(pageRequest.getPageNum(), pageRequest.getPageSize());
        return new PageResult<>(getSysUserByDepartmentCodeExample(fkDepartmentCode, keyword), page.getTotal());
    }

    @Override
    public PageResult<SysUser> getSysUserPageList(String keyword, PageRequest pageRequest) {
        Page<?> page = PageUtil.startPageAllowNull(pageRequest.getPageNum(), pageRequest.getPageSize());
        return new PageResult<>(getSysUserExample(keyword), page.getTotal());
    }


    /**
     * 更新用户状态
     *
     * @param id
     * @param state
     * @return
     */
    @Override
    public int updateSysUserState(String id, int state) {
        HashMap<String, Object> hashMap = new HashMap<>(2);
        hashMap.put("id", id);
        hashMap.put("state", state);
        return sysUserMapper.updateSysUserState(hashMap);
    }

    /**
     * 修改用户密码
     *
     * @param id         用户id
     * @param oldPwd     旧密码
     * @param newPwd     新密码
     * @param confirmPwd 确认密码
     * @return
     */
    @Override
    public int updateSysUserPassword(String id, String oldPwd, String newPwd, String confirmPwd) {
        Example example = new Example(SysUser.class);
        example.createCriteria().andEqualTo("id", id);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        SysUser sysUser = sysUserMapper.selectOneByExample(example);
        //判断旧密码不能为空
        if (StringUtil.isEmpty(oldPwd)) {
            throw LogicException.of("旧密码不能为空！");
        }
        //判断新密码不能为空
        if (StringUtil.isEmpty(newPwd)) {
            throw LogicException.of("新密码不能为空！");
        }
        //判断确认密码不能为空
        if (StringUtil.isEmpty(confirmPwd)) {
            throw LogicException.of("确认密码不能为空！");
        }
        //判断输入的旧密码是否正确
        boolean matches = encoder.matches(oldPwd, sysUser.getPassword());
        if (!matches) {
            throw LogicException.of("输入的旧密码不正确！");
        }
        //判断新密码和确认密码是否一致
        if (!newPwd.equals(confirmPwd)) {
            throw LogicException.of("两次输入的密码不一致！");
        }
        //加密新密码
        String password = new BCryptPasswordEncoder().encode(newPwd);
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("password", password);
        return sysUserMapper.updatePassword(map);
    }

    /**
     * 修改用户信息
     *
     * @param id
     * @param name
     * @param loginCode
     * @param email
     * @param phone
     * @return
     */
    @Override
    public int updateSysUserInfo(String id, String name, String loginCode, String email, String phone) {
        //查询是否存在登录名
        Example loginCodeExample = new Example(SysUser.class);
        loginCodeExample.createCriteria().andEqualTo("loginCode",loginCode);
        int loginCodes = sysUserMapper.selectCountByExample(loginCodeExample);
        if (loginCodes > 0){
            throw LogicException.of("该登陆帐号已经存在请重新输入！");
        }
        //查询邮箱是否存在
        Example eamilExample = new Example(SysUser.class);
        eamilExample.createCriteria().andEqualTo("email",email);
        int eamilExamples = sysUserMapper.selectCountByExample(eamilExample);
        if (eamilExamples > 0){
            throw LogicException.of("该邮箱已经存在请重新输入！");
        }
        //查询手机号码是否存在
        Example phoneExample = new Example(SysUser.class);
        phoneExample.createCriteria().andEqualTo("phone",phone);
        int phoneExamples = sysUserMapper.selectCountByExample(phoneExample);
        if (phoneExamples > 0){
            throw LogicException.of("该手机号码已经存在请重新输入！");
        }
        Map<String,Object> map = new HashMap<>(5);
        map.put("id",id);
        map.put("name",name);
        map.put("loginCode",loginCode);
        map.put("email",email);
        map.put("phone",phone);
        return sysUserMapper.updateUserinfo(map);
    }

    /**
     * 获取用户列表、用户分页列表公用方法
     *
     * @param keyword
     * @return
     */
    private List<SysUser> getSysUserByDepartmentCodeExample(String fkDepartmentCode, String keyword) {
        if (!StringUtil.isEmpty(fkDepartmentCode)) {
            Example example = new Example(SysUser.class);
            example.createCriteria()
                    .andEqualTo("fkDepartmentCode", fkDepartmentCode)
                    .andLike("name", SqlUtil.likeEscapeH(keyword))
                    .orLike("loginCode", SqlUtil.likeEscapeH(keyword))
                    .orLike("email", SqlUtil.likeEscapeH(keyword))
                    .orLike("phone", SqlUtil.likeEscapeH(keyword));
            example.orderBy("addTime").desc();
            return sysUserMapper.selectByExample(example);
        } else {
            return new ArrayList<>();
        }
    }

    private List<SysUser> getSysUserExample(String keyword) {
        Example example = new Example(SysUser.class);
        example.createCriteria()
                .andLike("name", SqlUtil.likeEscapeH(keyword))
                .orLike("loginCode", SqlUtil.likeEscapeH(keyword))
                .orLike("email", SqlUtil.likeEscapeH(keyword))
                .orLike("phone", SqlUtil.likeEscapeH(keyword));
        example.orderBy("addTime").desc();
        return sysUserMapper.selectByExample(example);
    }

}
